package com.yx.xinruitu.lbxupdate.controller;

import com.alibaba.fastjson.JSONObject;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.exception.HttpProcessException;
import com.yx.xinruitu.controller.base.BaseController;
import com.yx.xinruitu.entity.Staff;
import com.yx.xinruitu.lbxupdate.entity.WxServerInfo;
import com.yx.xinruitu.lbxupdate.service.Wx_StaffService;
import com.yx.xinruitu.service.IQuestionService;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ViewController extends BaseController {

    private final IQuestionService questionService;
    private final Wx_StaffService wxStaffService;

    public ViewController(Wx_StaffService wxStaffService, IQuestionService questionService) {
        this.wxStaffService = wxStaffService;
        this.questionService = questionService;
    }

    /**
     * pei zhi fuwuqi
     */
    @GetMapping("/wxServer")
    @ResponseBody
    public String wxServer(HttpServletRequest request) {
        return request.getParameter("echostr");
    }
    /*  主页*/
    @RequestMapping("/goWxIndex")
    public String goWxIndex(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map, @RequestParam @Nullable String id) throws HttpProcessException {
        Staff staff = getStaff(request, response, map, id);
        assert staff != null;
        if (staff.getIsCompletion() != null && staff.getIsCompletion().equals("yes")) {
            map.put("staff",staff);
            return "page/exam/wxIndex";
        }else {
            List<String> company = wxStaffService.getCompany();
            map.put("items",company);
            map.put("msg", "您还没有完善信息,请先完善信息");
            map.put("url", "goWxIndex");
            return "InforCompletion";
        }
    }

    /*点击初赛和复赛答题请求 由button 的url 请求该接口
    * Integer answerType 答题类型 1 初赛  2 复赛
    * */
    @RequestMapping("/answer")
    public String goView(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map, @RequestParam @Nullable String id, @RequestParam  Integer answerType) throws HttpProcessException {
        Staff staff = getStaff(request, response, map, id);
        if (staff == null) return null;
        Integer staffAnswerCount = 0;
        if (answerType==1){
            staffAnswerCount = staff.getCsCount();
        }
        if (answerType==2){
            staffAnswerCount = staff.getFsCount();
        }
        if (staff.getIsCompletion() != null && staff.getIsCompletion().equals("yes")&&staffAnswerCount>0) {
                    String url="/exam/startExam/"+answerType;
                    return "redirect:"+url;
                } else if (staffAnswerCount<=0){
                    try {
                        response.setContentType("text/html; charset=utf-8");
                        response.getWriter().print("<h1 style='color:red;width:50%;margin: 100px auto;'><p>每人只能答题两次,</p><p>您的答题次数已经到达上线!</p><p>不可再答题.</p></h1></br>");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    map.put("msg", "您还没有完善信息,请先完善信息");
                    map.put("answerType", answerType);
                    map.put("url", "answer");
                    return "InforCompletion";
                }
                return null;
    }
    /*用户注册并已经补全了信息*/
    private Staff getStaff(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map, String id) throws HttpProcessException {
        String openid = "";
        if (request.getParameter("code") != null && !request.getParameter("code").equals("")) {
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WxServerInfo.APPID + "&secret=" + WxServerInfo.APPSECRET + "&code=" + request.getParameter("code") + "&grant_type=authorization_code";
            HttpConfig httpConfig = HttpConfig.custom().url(url);
            String user_access_token = HttpClientUtil.get(httpConfig);
            JSONObject object = JSONObject.parseObject(user_access_token);
            openid = (String) object.get("openid");
        }else if (id != null && !id.equals("")) {

            openid = id;
        }
        if (openid.equals("")){
            try {
                response.setContentType("text/html; charset=utf-8");
                response.getWriter().print("<h1 style='color:red;width:50%;margin: 100px auto;'>非法访问,请使用宝鸡工会微信公众号进行答题!</h1>");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        Staff staff = wxStaffService.isCompletion(openid);
        map.put("staff", staff);
        request.getSession().setAttribute("staffid",staff.getId());
        request.getSession().setAttribute("openId",staff.getOpenId());
        return staff;
    }

    /*模拟答题入口*/
    @RequestMapping("/mockAnswer")
    public  String mockAnswer(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map, @RequestParam @Nullable String id, @RequestParam @Nullable Integer answerType) throws HttpProcessException {
        Staff staff = getStaff(request, response, map, id);
        assert staff != null;
        if (staff.getIsCompletion() != null && staff.getIsCompletion().equals("yes")){
            String url="/exam/startExam/"+"0";
            return "redirect:"+url;
        }else {
            List<String> company = wxStaffService.getCompany();
            map.put("items",company);
            map.put("msg", "您还没有完善信息,请先完善信息");
            map.put("url", "mockAnswer");
            return "InforCompletion";
        }
    }
    /*题库学习入口*/
    @RequestMapping("/questionBank")
    public  String questionBank(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map, @RequestParam @Nullable String id) throws HttpProcessException {
        Staff staff = getStaff(request, response, map, id);
        assert staff != null;
        if (staff.getIsCompletion() != null && staff.getIsCompletion().equals("yes")){
            map.put("staff",staff);
            return "page/exam/questionBank";
        }else {
            map.put("msg", "您还没有完善信息,请先完善信息");
            map.put("url", "mockAnswer");
            List<String> company = wxStaffService.getCompany();
            map.put("items",company);
            return "InforCompletion";
        }
    }
    /*getQuestionListByPage*/
    @GetMapping("/getQuestionListByPage")
    @ResponseBody
    public HashMap<String, Object> getQuestionListByPage(@RequestParam Integer currIndex)  {

        return questionService.getQuestionListByPage(this.getParameterMap(), 10, currIndex);
    }

    @PostMapping("/infoCompletion")
    @ResponseBody
    public boolean infoCompletion(Staff staff) {
        staff.setIsCompletion("yes");
        int i = wxStaffService.updateStaff(staff);
        return i == 1;
    }


}
